package cn.lml.lession.auth.config;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

@Component("defaultAuthorizationService")
public class DefaultAuthorizationService implements AuthorizationService {

    private final static Logger logger = LoggerFactory.getLogger(DefaultAuthorizationService.class);

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
        boolean isPermission = false;
        String requestURI = request.getRequestURI();
        if(StringUtils.isEmpty(requestURI)){
            return isPermission;
        }
        //匿名用户不能经过授权
        if(authentication!=null&&!authentication.getPrincipal().equals("anonymousUser")&&
                authentication.isAuthenticated()) {

            String userName = (String)authentication.getPrincipal();
            //读取用户所有的Url,可以通过用户服务拿到当前用户服务拿到该用户的能访问的地址
            Set<String> urls = new HashSet<>();
            urls.add("/**");
            for (String  url : urls) {
                if (antPathMatcher.match(url, requestURI)) {
                    isPermission = true;
                    logger.info("用户[{}]鉴权,鉴权地址为:{}.",userName,requestURI);
                    break;
                }
            }
            return isPermission;
        }
        return isPermission;
    }
}

